package com.example.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.List;

public class ProductAdapterMain extends RecyclerView.Adapter<ProductAdapterMain.ProductViewHolder> {

    private final List<Product> productList;
    private final Context context;
    private final DBHelper dbHelper;

    public ProductAdapterMain(List<Product> productList, Context context) {
        this.productList = productList;
        this.context = context;
        dbHelper = new DBHelper(context);
    }

    @NonNull
    @Override
    public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_product, parent, false);
        return new ProductViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ProductViewHolder holder, int position) {
        Product product = productList.get(position);
        holder.tvName.setText(product.getName());
        holder.tvPrice.setText(String.format("￥%.2f", product.getPrice()));
        holder.tvDescription.setText(product.getDescription());

        System.out.println("bbb::" +product.getImagePath());
        // 使用Glide加载图片
        Glide.with(context)
                .load(context.getResources().getIdentifier(product.getImagePath(), "drawable", context.getPackageName())) // 动态加载
                .placeholder(R.drawable.place)
                .into(holder.ivProductImage);


        holder.itemView.setOnClickListener(v -> {
            Intent intent = new Intent(context, com.example.ProductDetailActivity.class);
            intent.putExtra("product_id", product.getId());
            intent.putExtra("product_name", product.getName());
            intent.putExtra("product_description", product.getDescription());
            intent.putExtra("product_price", product.getPrice());
            intent.putExtra("product_image", product.getImagePath());
            intent.putExtra("seller_id",1000 );
            context.startActivity(intent);
        });

        holder.btnUpdate.setOnClickListener(v -> {
          /*  Intent intent = new Intent(context, AddProductActivity.class);
            intent.putExtra("product_id", product.getId());
            intent.putExtra("product_name", product.getName());
            intent.putExtra("product_description", product.getDescription());
            intent.putExtra("product_price", product.getPrice());
            context.startActivity(intent);*/
            showUpdateDialog(product,position);
        });

        holder.btnDelete.setOnClickListener(v -> {
            dbHelper.getWritableDatabase().delete("products", "product_id = ?", new String[]{String.valueOf(product.getId())});
            productList.remove(position);
            notifyItemRemoved(position);
            Toast.makeText(context, "商品已删除", Toast.LENGTH_SHORT).show();
        });


    }

    private void showUpdateDialog(Product product, int position) {
        // 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("更新商品信息");

        // 加载自定义布局
        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_update_product, null);
        builder.setView(dialogView);

        // 初始化对话框中的控件
        EditText etName = dialogView.findViewById(R.id.etName);
        EditText etDescription = dialogView.findViewById(R.id.etDescription);
        EditText etPrice = dialogView.findViewById(R.id.etPrice);

        // 设置当前商品信息到输入框
        etName.setText(product.getName());
        etDescription.setText(product.getDescription());
        etPrice.setText(String.valueOf(product.getPrice()));

        builder.setPositiveButton("保存", (dialog, which) -> {
            // 获取用户输入的数据
            String updatedName = etName.getText().toString().trim();
            String updatedDescription = etDescription.getText().toString().trim();
            String updatedPriceStr = etPrice.getText().toString().trim();

            // 校验输入
            if (updatedName.isEmpty() || updatedDescription.isEmpty() || updatedPriceStr.isEmpty()) {
                Toast.makeText(context, "所有字段必须填写", Toast.LENGTH_SHORT).show();
                return;
            }

            double updatedPrice = Double.parseDouble(updatedPriceStr);

            // 更新数据库
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put("name", updatedName);
            values.put("description", updatedDescription);
            values.put("price", updatedPrice);

            int rowsAffected = db.update("products", values, "product_id = ?", new String[]{String.valueOf(product.getId())});
            db.close();

            if (rowsAffected > 0) {
                // 更新 RecyclerView 的数据
                product.setName(updatedName);
                product.setDescription(updatedDescription);
                product.setPrice(updatedPrice);
                notifyItemChanged(position);

                Toast.makeText(context, "商品信息已更新", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "更新失败，请重试", Toast.LENGTH_SHORT).show();
            }
        });

        builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
        builder.show();
    }


    @Override
    public int getItemCount() {
        return productList.size();
    }

    public static class ProductViewHolder extends RecyclerView.ViewHolder {
        TextView tvName, tvPrice, tvDescription;
        ImageView ivProductImage;
        Button btnDelete;
        Button btnUpdate;

        public ProductViewHolder(@NonNull View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tvProductName);
            tvPrice = itemView.findViewById(R.id.tvProductPrice);
            tvDescription = itemView.findViewById(R.id.tvProductDescription);
            ivProductImage = itemView.findViewById(R.id.ivProductImage);
            btnUpdate = itemView.findViewById(R.id.btnUpdate);

            btnDelete = itemView.findViewById(R.id.btnDelete);
        }
    }
}
